package com.trex.lwlsh.util;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
import java.io.IOException;

/**
 * Create by Trex on 2018/1/13
 */
public class ReadConfigUtil {

    /**
     * 测试方法
     * @param args
     */
    public static void main(String[] args) {
        System.out.println(readconfig("Templatepath2"));

    }

    /**
     * 配置读取信息
     * @param elementName
     * @return
     */
    public  static String readconfig(String elementName) {
        System.out.println("elementName:"+elementName);
        String currentPath = System.getProperty("user.dir");
        // System.out.println(System.getProperty("user.dir"));
        String Key=null;
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = factory.newDocumentBuilder();
            Document doc = db.parse(new File(currentPath+"/config.xml"));
            Element elmtInfo = doc.getDocumentElement();
            //	System.out.println(elmtInfo);
            NodeList nodes = elmtInfo.getChildNodes();
            //System.out.println(nodes);
            for (int i = 0; i < nodes.getLength(); i++)
            {
                Node result = nodes.item(i);
                //System.out.println(result.getNodeName()+":"+Node.ELEMENT_NODE);
                if (result.getNodeType() == Node.ELEMENT_NODE && result.getNodeName().equals(elementName)){
                    Key =result.getTextContent();
                    //System.out.println(Key);

                }
            }

        }
        catch (ParserConfigurationException e)
        {
            e.printStackTrace();
        }
        catch (SAXException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return Key;

    }


}
